import requests
from datetime import datetime
import os
import random
##cron: 10 10 * * *
##new Env("修车指南")

def get_env_variables():
    """从青龙环境变量获取配置"""
    env_value = os.getenv('xczn')
    if env_value and '#' in env_value:
        parts = env_value.split('#', 1)
        PHPSESSID = parts[0].strip()
        token = parts[1].strip()
        return PHPSESSID, token
    else:
        print("环境变量 xczn 未设置或格式错误，请检查!")
        return None, None

def get_emoji_by_message(msg):
    """根据消息内容返回相应的表情符号"""
    msg_lower = msg.lower()
    
    # 成功相关表情
    success_emojis = ["🎉", "✅", "👍", "🚀", "✨", "💯", "🏆", "🎊"]
    # 失败相关表情
    fail_emojis = ["😢", "❌", "⚠️", "😔", "💔", "🚫"]
    # 信息相关表情
    info_emojis = ["ℹ️", "📝", "📋", "🔍", "💡"]
    # 汽车相关表情
    car_emojis = ["🚗", "🚙", "🏎️", "🚘", "🔧", "🛠️", "⛽"]
    
    # 根据消息内容判断使用哪种表情
    if any(word in msg_lower for word in ["成功", "完成", "获得", "签到", "感谢", "恭喜"]):
        return random.choice(success_emojis)
    elif any(word in msg_lower for word in ["失败", "错误", "异常", "无效", "过期", "拒绝"]):
        return random.choice(fail_emojis)
    elif any(word in msg_lower for word in ["已签到", "重复", "已经"]):
        return "⏰"  # 时间相关，表示已经做过
    else:
        # 默认返回汽车相关表情
        return random.choice(car_emojis)

def send_wechat_webhook(message):
    """发送消息到企业微信机器人"""
    webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c4ed66c7-ea68-4b51-be3f-8319beb4504d"
    
    # 根据消息内容获取表情
    emoji = get_emoji_by_message(message)
    
    payload = {
        "msgtype": "text",
        "text": {
            "content": f"{emoji} 修车指南 {emoji}\n⏰ 时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n📊 状态：{message}\n🚗 祝您用车愉快！",
           # "mentioned_list": ["@all"]  # 需要@所有人时保留，否则可删除
        }
    }

    try:
        response = requests.post(webhook_url, json=payload, timeout=8)
        response.raise_for_status()
        result = response.json()
        
        if result.get('errcode') != 0:
            print(f"企业微信接口错误：{result.get('errmsg')}")
            return False
        return True
    except Exception as e:
        print(f"消息推送失败：{str(e)}")
        return False

def main():
    # 从环境变量获取配置
    PHPSESSID, token = get_env_variables()
    if not PHPSESSID or not token:
        error_msg = "无法获取有效的 PHPSESSID 或 token，请检查环境变量设置"
        print(f"❌ {error_msg}")
        send_wechat_webhook(error_msg)
        return

    # 原有签到逻辑
    url = "https://xczn.xyz/index/signin/dosign"
    cookies = {
        "uid": "434948",
        "level": "0",
        "viptimes": "0",
        "token": token,
        "PHPSESSID": PHPSESSID,
    }
    
    headers = {
        "Host": "xczn.xyz",
        "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.200 Mobile Safari/537.36",
        "X-Requested-With": "XMLHttpRequest",
        "Origin": "https://xczn.xyz",
        "Referer": "https://xczn.xyz/index/signin/index.html",
    }

    try:
        with requests.Session() as session:
            session.headers.update(headers)
            response = session.post(url, cookies=cookies, timeout=10)
            response.raise_for_status()

            # 获取签到消息
            msg = response.json().get('msg', '未获取到有效消息')
            print(f"🎯 原始签到结果：{msg}")

            # 推送消息到企业微信
            if send_wechat_webhook(msg):
                print("✅ 消息已成功推送至企业微信")
            else:
                print("❌ 消息推送失败，请检查日志")

    except requests.exceptions.JSONDecodeError:
        error_msg = "签到响应解析失败"
        print(f"❌ {error_msg}")
        send_wechat_webhook(error_msg)
    except requests.exceptions.RequestException as e:
        error_msg = f"签到请求失败：{str(e)}"
        print(f"❌ {error_msg}")
        send_wechat_webhook(error_msg)

if __name__ == "__main__":
    print("🚗 开始执行修车指南签到任务...")
    main()
    print("🏁 任务执行完毕！")